export function createRoute(record, location) {
  let res = []
  // 如果能匹配到record
  if (record) {
    while (record) {
      res.unshift(record)
      record = record.parent
    }
  }
  return {
    ...location,
    matched: res
  }
}

function runQuene(quene, iterator, cb) {
  // 异步迭代
  function step(index) {
    if(index >= quene.length) {
      return cb()
    }

    let hook = quene[index]
    iterator(hook, () => {
      step(index + 1)
    })
  }
  step(0)
}

class History {
  constructor(router) {
    this.router = router

    // 默认当创建history时，路径应该是 '/' 并且匹配到的记录是[]
    this.current = createRoute(null, {
      path: '/'
    })
  }

  listen(cb) {
    this.cb = cb
  }

  transitionTo(location, onComplete) {
    // 这个route就是当前最新的匹配到的结果
    let route = this.router.match(location)
    // 防止重复跳转
    if (location == this.current.path && route.matched.length == this.current.matched.length) {
      return
    }
    
    // 在更新之前先调用注册好的钩子函数
    let quene = [].concat(this.router.beforeHooks)

    const iterator = (hook, next) => {
      hook(this.current, route, () => {
        next()
      })
    }

    runQuene(quene, iterator, () => {
      // 在更新之前先调用注册好的导航守卫
      this.updateRoute(route)

      onComplete || onComplete()
    })
  }

  updateRoute(route) {
    this.current = route

    // 在current变化的同时改变对_route赋值
    this.cb && this.cb(route)
    /**
     * 视图重新渲染
     * 1. 模板中要用
     * 2. current得是响应式的
     * 
     */
  }
}
export default History